package com.TropicalFlavor.controller;

import com.TropicalFlavor.po.MarketGoods;
import com.TropicalFlavor.po.MarketUser;
import com.TropicalFlavor.service.userService;
import com.TropicalFlavor.token.TokenProcessor;
import com.TropicalFlavor.tool.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
@Slf4j
public class userController
{
    @Resource
    private userService service;

    @RequestMapping(value = "/logout.do")
    public String logout(HttpServletRequest request)
    {
        try
        {
            request.getSession().removeAttribute("marketUser");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return "redirect:/home.do";
        }
        return "redirect:/";
    }

    @RequestMapping(value = "/login.do", method = RequestMethod.GET)
    public String login(HttpServletRequest request, Model model)
    {
        String token = TokenProcessor.getInstance().makeToken();
        log.info("进入登录界面，token为：" + token);
        request.getSession().setAttribute("token", token);
        model.addAttribute("token", token);
        return "page/login_page";
    }

    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public String login(HttpServletRequest request, @RequestParam String sNum,
                        @RequestParam String Password, @RequestParam boolean isAdmin,
                        @RequestParam String token)
    {
        String loginToken = (String)request.getSession().getAttribute("token");
        if(StringUtils.getInstance().isNullOrEmpty(sNum) || StringUtils.getInstance().isNullOrEmpty(Password))
        {
            return "redirect:/login.do";
        }
        if (StringUtils.getInstance().isNullOrEmpty(token) || !token.equals(loginToken))
        {
            return "redirect:/login.do";
        }
        boolean isLoginSuccess = checkLogin(sNum, Password, isAdmin, request);
        if(!isLoginSuccess)
        {
            return "redirect:/login.do";
        }
        //request.getSession().setAttribute("marketUser", user);
        return "redirect:/";
    }

    //查看用户基本信息
    @RequestMapping(value = "/personal_info.do")
    public String personInfo(HttpServletRequest request, Model model)
    {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");
        if(StringUtils.getInstance().isNullOrEmpty(user))
            return "redirect:/login.do";
        String personalInfoToken = TokenProcessor.getInstance().makeToken();
        request.getSession().setAttribute("personalInfoToken", personalInfoToken);
        model.addAttribute("token", personalInfoToken);
        model.addAttribute("marketUser", user);
        return "page/personal/information";
    }

    @RequestMapping(value = "/goToEditPersonalInfo.do")
    public String goToEditPersonInfo(HttpServletRequest request, Model model)
    {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");
        model.addAttribute("marketUser", user);
        return "page/editperson";
    }

    //修改用户信息
    @RequestMapping(value = "/editPersonalInfo.do", method = RequestMethod.POST)
    //@ResponseBody
    public String editPersonalInfo(HttpServletRequest request,
                                @RequestParam(required = false) String Uname,
                                @RequestParam(required = false) String Password,
                                @RequestParam(required = false) String PhoneNum,
                                @RequestParam(required = false) String Email
                                )
    {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");

        //用户还没有登录
        if(StringUtils.getInstance().isNullOrEmpty(user))
            return "redirect:/goToEditPersonalInfo.do";

        String editPersonalToken =(String)request.getSession().getAttribute("personalInfoToken");
        if(StringUtils.getInstance().isNullOrEmpty(editPersonalToken))
            return "redirect:/goToEditPersonalInfo.do";
        else
            request.getSession().removeAttribute("editPersonalToken");

        //符合要求即可替换，否则重新加载页面
        if(!Uname.isEmpty())
        {
            if(Uname.length() <= 30)
                user.setUname(Uname);
            else
                return "redirect:/goToEditPersonalInfo.do";
        }

        if(!Password.isEmpty())
        {
            if(Password.length() <=16)
                user.setPassword(Password);
            else
                return "redirect:/goToEditPersonalInfo.do";
        }

        if(!PhoneNum.isEmpty())
        {
            if(PhoneNum.length() <=11)
                user.setPhoneNum(PhoneNum);
            else
                return "redirect:/goToEditPersonalInfo.do";
        }

        if(!Email.isEmpty())
        {
            if(Email.length() <= 50)
                user.setEmail(Email);
            else
                return "redirect:/goToEditPersonalInfo.do";
        }

//        if(Password != null && Password.length() <= 16)
//            user.setPassword(Password);
//        else
//            return "redirect:/goToEditPersonalInfo.do";

//        if(PhoneNum != null && PhoneNum.length() <= 11)
//            user.setPhoneNum(PhoneNum);
//        else
//            return "redirect:/goToEditPersonalInfo.do";
//
//        if(Email != null && Email.length() <= 50)
//            user.setEmail(Email);
//        else
//            return "redirect:/goToEditPersonalInfo.do";

        boolean isEditSuccess = service.ChangeInfo(user);
        if(!isEditSuccess)
            return "redirect:/goToEditPersonalInfo.do";

        request.getSession().setAttribute("marketUser", user);
        return "redirect:/personal_info.do";
    }

    //用户上传商品
    @RequestMapping(value = "/insertGoods.do", method = RequestMethod.POST)
    public String insertGoods(@RequestParam(required = false) MultipartFile image,
                              @RequestParam String GID,
                              @RequestParam String Name,
                              @RequestParam String Kind,
                              @RequestParam Double Price,
                              @RequestParam Integer Number,
                              @RequestParam int action,
                              HttpServletRequest request, Model model)
    {
        MarketUser user = (MarketUser) request.getSession().getAttribute("marketUser");
        model.addAttribute("marketUser", user);

        if(GID.isEmpty() || Name.isEmpty() || Kind == null || Price == null || Number == null)
        {
            return "page/publish_product";
        }

        if(action == 1)
        {
            MarketGoods goods = new MarketGoods();
            goods.setGID(GID);
            goods.setName(Name);
            goods.setKind(Kind);
            goods.setPrice(Price);
            goods.setNumber(Number);
        }
    }


    //验证登录
    public boolean checkLogin(String sNum, String Password, boolean isAdmin, HttpServletRequest request)
    {
        boolean isLoginSuccess = service.Login(sNum, Password, isAdmin);
        if(!isLoginSuccess)
            return false;
        String UID = "";
        if(isAdmin)
        {
            UID = "ADMI" + sNum;
        }
        else
        {
            UID = "NORM" + sNum;
        }
        MarketUser user = service.selectByPrimaryKey(UID);
        if(null == user)
            return false;
        request.getSession().setAttribute("marketUser", user);
        return true;
    }
}
